package com.tenton.filter;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Date: 2021/1/14
 * @Author: Tenton
 * @Description:
 */
public class AutologinFilter implements Filter {
    private String excludedPage;
    private String[] excludedPages;
    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession(true);

        // 定义表示变量 并验证用户请求URL 是否包含不过滤路径
        boolean flag = false;
        for (String page:excludedPages) {
            if (req.getRequestURI().equals(page)){
                System.out.println("放行"+page);
                flag = true;
            }
        }
        if(flag){
            chain.doFilter(request,response);
        }

        Cookie[] cookies = req.getCookies();
        String automatic = "";
        for (Cookie cookie:cookies) {
            if ("flag".equals(cookie.getName())){
                automatic = "flag";
            }
        }
        if ("flag".equals(automatic)){
            //存在名字为flag的Cookie，选过30自动登录放行 59.110.65.106
            chain.doFilter(request, response);
        }

        String user = (String) session.getAttribute("user");
        String url=req.getRequestURI();
        if(user==null || "".equals(user))
        {
            //判断获取的路径不为空且不是访问登录页面或执行登录操作时跳转
            if(url!=null && !url.equals("") && ( url.indexOf("Login")<0 && url.indexOf("login")<0 ))
            {
                resp.sendRedirect("login.jsp");
                return ;
            }
        }
        //无论是否自动登陆,都放行资源
        chain.doFilter(request, response);
    }

    public void init(FilterConfig config) throws ServletException {
        //此处的ignores就是在web.xml定义的名称一样。
        excludedPage = config.getInitParameter("neglect");
        if (excludedPage != null && excludedPage.length() > 0){
            excludedPages = excludedPage.split(",");
        }
    }
}
